package com.distributed.common.message;

import com.distributed.common.Constant;

import net.sf.json.JSONObject;

public class LogicServInfoMessage extends BaseMessage {
	public final static String ERROR = new LogicServInfoMessage(
			"255.255.255.255", -1, -1).setMsg("error:invaild message")
			.toString();

	public LogicServInfoMessage() {
		super();
		setId(Constant.LOGIC_SERVINFO_MESSAGE);
	}

	public LogicServInfoMessage(String ip, int port, long lease) {
		super();
		setId(Constant.LOGIC_SERVINFO_MESSAGE);
		setIp(ip);
		setPort(port);
		setLease(lease);
	}

	public static String getName() {
		return Constant.LOGIC_SERVINFO_MESSAGE_NAME;
	}

	public void setIp(String ip) {
		argv.put(Constant.IP_S, ip);
	}

	public String getIp() {
		return argv.get(Constant.IP_S);
	}

	public void setPort(int port) {
		argv.put(Constant.PORT_S, String.valueOf(port));
	}

	public int getPort() {
		String tmp = argv.get(Constant.PORT_S);
		try {
			return Integer.valueOf(tmp);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return -1;
	}

	public long getLease() {
		String tmp = argv.get(Constant.LEASE);
		long lease = 0;
		try {
			lease = Long.valueOf(tmp);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return -1;
		}
		return lease + System.currentTimeMillis();
	}

	public void setLease(long lease) {
		argv.put(Constant.LEASE, String.valueOf(lease));
	}

	public String getMsg() {
		return argv.get(Constant.MSG);
	}

	public LogicServInfoMessage setMsg(String msg) {
		argv.put(Constant.MSG, msg);
		return this;
	}

	public static LogicServInfoMessage getFromString(String message) {
		JSONObject jsonobject = JSONObject.fromObject(message);
		if (jsonobject == null) {
			return null;
		}
		return getFromJSON(jsonobject);
	}

	public static LogicServInfoMessage getFromJSON(JSONObject jsonobj) {
		BaseMessage baseMessage = new CancelMessage();
		BaseMessage baseMsg = BaseMessage.getFromJSON(jsonobj, baseMessage);
		if (baseMsg == null
				|| baseMsg.getId() != Constant.LOGIC_SERVINFO_MESSAGE) {
			return null;
		}
		String ip = baseMsg.getArgvValue(Constant.IP_S);
		if (ip == null || "".equals(ip)) {
			return null;
		}
		String port_s = baseMsg.getArgvValue(Constant.PORT_S);
		try {
			Integer.valueOf(port_s);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}
		String lease = baseMsg.getArgvValue(Constant.LEASE);
		try {
			Long.valueOf(lease);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}

		return (LogicServInfoMessage) baseMsg;
	}

	public JSONObject toJSON() {
		return super.toJSON();
	}

	public String toString() {
		return toJSON().toString();
	}
}
